package com.nondo.dean.saprfc.service;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import com.nondo.dean.common.web.View;
import com.nondo.dean.saprfc.common.SapUtil;
import com.nondo.dean.saprfc.common.Util;
import com.nondo.dean.saprfc.domain.OrderStatusTrackingResult;
import com.nondo.dean.saprfc.model.OrderSubjectBean;
import com.sap.conn.jco.JCoFunction;
import com.sap.conn.jco.JCoTable;

/**
 * @author xiaofan
 * @Description:
 * @date 2018-04-2517:07
 * @Version
 */
@Component
public class CrmOrderStautsService {

    @Autowired
    RestTemplate restTemplate;

    private static final Logger logger = LoggerFactory.getLogger(CrmOrderStautsService.class);

    /**
     * 获取sap返回的订单状态跟踪
     * 
     * @param sapCode
     * @param sapClient
     * @return
     */
    public List<OrderStatusTrackingResult> getOrderStatus(String sapCode, String sapClient) {
        List<OrderStatusTrackingResult> orderStatusTrackingList = new ArrayList<>();
        JCoFunction function = SapUtil.getFunction(sapClient, "Z_ND_OA_STATUS_DETAILS");
        function.getImportParameterList().setValue("VBELN", sapCode);// SAP销售订单号
        SapUtil.executeFunction(sapClient, function);
        JCoTable table = function.getTableParameterList().getTable("IT_OUTPUT");
        for (int i = 0; i < table.getNumRows(); i++) {

            OrderStatusTrackingResult orderStatusTrackingBean =
                new OrderStatusTrackingResult(table.getString("VBELN"), table.getString("BSTNK"),
                    Util.delFirstZero(table.getString("POSNR")), table.getString("KUNNR_NAME"),
                    table.getString("MATNR"), table.getString("ARKTX"), table.getString("ZSCBZ"),
                    table.getString("KWMENG"), table.getString("NETPR"), table.getString("ZSTAUS"),
                    table.getString("ERDAT"), Util.delFirstZero(table.getString("AUFNR")), table.getString("FTRMI"),
                    table.getString("GSTRP"), table.getString("GLTRP"), table.getString("BUDAT"),
                    table.getString("BEZEI"), table.getString("FDAT"), table.getString("ZJIANSHU"),
                    table.getString("TXTPA"), table.getString("LTXA1"), table.getString("EBELN"),
                    table.getString("EBELP"), table.getString("SODAT"), table.getString("BUDAT_PO")

                );
            orderStatusTrackingList.add(orderStatusTrackingBean);
            table.nextRow();
        }

        return orderStatusTrackingList;
    }

    /**
     * 获取sap返回的订单状态 状态 1未发货 2已备货 3已发货
     * 
     * @param sapClient
     * @return
     */
    public Map<String, String> getSapOrderStautsTableData(String sapClient, OrderSubjectBean orderSubject) {
        Map<String, String> map = new LinkedHashMap<>();
        JCoFunction function = SapUtil.getFunction(sapClient, "Z_ND_CRM_001");
        function.getImportParameterList().setValue("IM_PONUM", orderSubject.getOrderCode());// 采购订单号
        SapUtil.executeFunction(sapClient, function);
        JCoTable table = function.getTableParameterList().getTable("EX_STATUS");
        for (int i = 0; i < table.getNumRows(); i++) {
            map.put("ponum", table.getString("PONUM"));
            map.put("status", table.getString("STATUS"));
            table.nextRow();
        }
        return map;
    }

    /**
     * 更新app订单发货状态 定时任务
     */
    public void updateAppOrderStauts(OrderSubjectBean orderSubject) {
        View<Map<String, String>> view = new View<Map<String, String>>();
        view.setData(getSapOrderStautsTableData(Util.SAP_CLIENT, orderSubject));
        restTemplate.postForEntity("http://dean-order/order/v1/inner/order/update/app/order/status", view,
            Integer.class).getBody();
    }

    /**
     * 查询已同步到SAP但未支付的订单 定时任务
     */
    public List<OrderSubjectBean> getWaittingToDeliverOrderList() {
        List<OrderSubjectBean> orderSubjectBeanList = null;

        ParameterizedTypeReference parameterizedTypeReference =
            new ParameterizedTypeReference<View<List<OrderSubjectBean>>>() {};

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<String> entity = new HttpEntity<String>(headers);

        ResponseEntity<View<List<OrderSubjectBean>>> response =
            restTemplate.exchange("http://dean-order/order/v1/inner/order/sync/list", HttpMethod.POST, entity,
                parameterizedTypeReference);
        View<List<OrderSubjectBean>> view = response.getBody();

        if (view.getCode() == View.STATE_OK) {
            orderSubjectBeanList = (List<OrderSubjectBean>)view.getData();
        }
        return orderSubjectBeanList;
    }

}
